package com.party.core.service.gatherInfo.biz;

import com.google.common.collect.Sets;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PinyinUtil;
import com.party.common.utils.StringUtils;
import com.party.core.model.activity.Activity;
import com.party.core.model.competition.CompetitionBusiness;
import com.party.core.model.gatherInfo.GatherInfoItinerary;
import com.party.core.model.gatherInfo.GatherInfoMember;
import com.party.core.model.gatherInfo.GatherInfoProject;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAct;
import com.party.core.model.member.MemberInfo;
import com.party.core.service.competition.ICompetitionBusinessService;
import com.party.core.service.gatherInfo.IGatherInfoItineraryService;
import com.party.core.service.gatherInfo.IGatherInfoMemberService;
import com.party.core.service.gatherInfo.IGatherInfoProjectService;
import com.party.core.service.member.IMemberInfoService;
import com.party.core.service.member.IMemberService;
import com.party.core.utils.MyBeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 信息收集业务
 *
 * @author Administrator
 */
@Service
public class GatherInfoMembersBizService {

    @Autowired
    private IMemberService memberService;
    @Autowired
    private IMemberInfoService memberInfoService;
    @Autowired
    private IGatherInfoItineraryService gatherInfoItineraryService;
    @Autowired
    private ICompetitionBusinessService competitionBusinessService;
    @Autowired
    private IGatherInfoProjectService gatherInfoProjectService;
    @Autowired
    private IGatherInfoMemberService gatherInfoMemberService;

    /**
     * 更新用户基本信息
     *
     * @param memberInfo
     * @param memberId
     */
    /*public Member updateMemberBaseInfo(GatherInfoMember memberInfo, String memberId) {
		Member memberNew = memberService.get(memberId);
		if (memberNew == null) {
			return null;
		}
		// 头像
		if (StringUtils.isNotEmpty(memberInfo.getLogo())) {
			memberNew.setLogo(memberInfo.getLogo());
		}
		// 真实姓名
		if (StringUtils.isNotEmpty(memberInfo.getRealname())) {
			memberNew.setFullname(PinyinUtil.filterEmoji(memberInfo.getRealname(), ""));
		}
		// 性别
		if (null != memberInfo.getSex()) {
			memberNew.setSex(memberInfo.getSex());
		}
		// 微信号
		if (StringUtils.isNotEmpty(memberInfo.getWechatNum())) {
			memberNew.setWechatNum(PinyinUtil.filterEmoji(memberInfo.getWechatNum(), ""));
		}
		// 公司
		if (StringUtils.isNotEmpty(memberInfo.getCompany())) {
			memberNew.setCompany(PinyinUtil.filterEmoji(memberInfo.getCompany(), ""));
		}
		// 职称
		if (StringUtils.isNotEmpty(memberInfo.getJobTitle())) {
			memberNew.setJobTitle(PinyinUtil.filterEmoji(memberInfo.getJobTitle(), ""));
		}
		// 行业
		if (StringUtils.isNotEmpty(memberInfo.getIndustryId())) {
			memberNew.setIndustry(memberInfo.getIndustryId());
		}
		// 城市
		if (StringUtils.isNotEmpty(memberInfo.getCityId())) {
			memberNew.setCity(memberInfo.getCityId());
		}
		// 个性签名
		if (StringUtils.isNotEmpty(memberInfo.getIntroduction())) {
			memberNew.setSignature(PinyinUtil.filterEmoji(memberInfo.getIntroduction(), ""));
		}
		memberService.update(memberNew);
		return memberNew;
	}*/

    /**
     * 更新用户附属信息
     *
     * @param infoMember
     * @param memberId
     */
	/*public void updateMemberSatelliteInfo(GatherInfoMember infoMember, String memberId) {
		MemberInfo memberInfo = memberInfoService.findByMemberId(memberId);
		if (memberInfo == null) {
			memberInfo = new MemberInfo();
		}
		memberInfo.setMemberId(memberId);
//		memberInfo.setSize(PinyinUtil.filterEmoji(infoMember.getSize(), ""));
		memberInfo.setIdCard(PinyinUtil.filterEmoji(infoMember.getIdCard(), ""));
		memberInfo.setBloodGroup(PinyinUtil.filterEmoji(infoMember.getBloodGroup(), ""));
		memberInfo.setMedicalHistory(PinyinUtil.filterEmoji(infoMember.getMedicalHistory(), ""));
		memberInfo.setContactMobile(PinyinUtil.filterEmoji(infoMember.getContactMobile(), ""));
		memberInfo.setContactName(PinyinUtil.filterEmoji(infoMember.getContactName(), ""));
		memberInfo.setContactRelation(PinyinUtil.filterEmoji(infoMember.getContactRelation(), ""));

		if (StringUtils.isEmpty(memberInfo.getId())) {
			memberInfoService.insert(memberInfo);
		} else {
			memberInfoService.update(memberInfo);
		}
	}*/

    /**
     * 前端-更新用户附属信息
     *
     * @param infoMember
     * @param memberId
     */
    public String updateMemberSatelliteInfo(MemberInfo infoMember, String memberId) {
        MemberInfo memberInfo = memberInfoService.findByMemberId(memberId);
        if (memberInfo == null) {
            memberInfo = new MemberInfo();
        }
        memberInfo.setMemberId(memberId);
        // memberInfo.setSize(PinyinUtil.filterEmoji(infoMember.getSize(), ""));
        memberInfo.setIdCard(PinyinUtil.filterEmoji(infoMember.getIdCard(), ""));
        memberInfo.setBloodGroup(PinyinUtil.filterEmoji(infoMember.getBloodGroup(), ""));
        memberInfo.setMedicalHistory(PinyinUtil.filterEmoji(infoMember.getMedicalHistory(), ""));
        memberInfo.setContactMobile(PinyinUtil.filterEmoji(infoMember.getContactMobile(), ""));
        memberInfo.setContactName(PinyinUtil.filterEmoji(infoMember.getContactName(), ""));
        memberInfo.setContactRelation(PinyinUtil.filterEmoji(infoMember.getContactRelation(), ""));
        memberInfo.setTaiwanCertificate(PinyinUtil.filterEmoji(infoMember.getTaiwanCertificate(), ""));
        memberInfo.setReturnCard(PinyinUtil.filterEmoji(infoMember.getReturnCard(), ""));
        memberInfo.setPassport(PinyinUtil.filterEmoji(infoMember.getPassport(), ""));
        memberInfo.setUseCertificate(infoMember.getUseCertificate());
        memberInfo.setBirthday(infoMember.getBirthday());
        if (StringUtils.isEmpty(memberInfo.getId())) {
            memberInfoService.insert(memberInfo);
        } else {
            memberInfoService.update(memberInfo);
        }

        return memberInfo.getId();
    }

    /**
     * 前端-更新用户基本信息
     *
     * @param memberInfo
     * @param memberId
     * @return
     */
    public Member updateMemberBaseInfo(Member memberInfo, String memberId) {
        Member memberNew = memberService.get(memberId);
        if (memberNew == null) {
            return null;
        }
        // 头像
        if (StringUtils.isNotEmpty(memberInfo.getLogo())) {
            memberNew.setLogo(memberInfo.getLogo());
        }
        // 真实姓名
        if (StringUtils.isNotEmpty(memberInfo.getFullname())) {
            memberNew.setFullname(PinyinUtil.filterEmoji(memberInfo.getFullname(), ""));
        }
        // 性别
        if (null != memberInfo.getSex()) {
            memberNew.setSex(memberInfo.getSex());
        }
        // 微信号
        if (StringUtils.isNotEmpty(memberInfo.getWechatNum())) {
            memberNew.setWechatNum(PinyinUtil.filterEmoji(memberInfo.getWechatNum(), ""));
        }
        // 公司
        if (StringUtils.isNotEmpty(memberInfo.getCompany())) {
            memberNew.setCompany(PinyinUtil.filterEmoji(memberInfo.getCompany(), ""));
        }
        // 职称
        if (StringUtils.isNotEmpty(memberInfo.getJobTitle())) {
            memberNew.setJobTitle(PinyinUtil.filterEmoji(memberInfo.getJobTitle(), ""));
        }
        // 行业
        if (StringUtils.isNotEmpty(memberInfo.getIndustry())) {
            memberNew.setIndustry(memberInfo.getIndustry());
        }
        // 城市
        if (StringUtils.isNotEmpty(memberInfo.getCity())) {
            memberNew.setCity(memberInfo.getCity());
        }
        // 个性签名
        if (StringUtils.isNotEmpty(memberInfo.getSignature())) {
            memberNew.setSignature(PinyinUtil.filterEmoji(memberInfo.getSignature(), ""));
        }
        memberService.update(memberNew);
        return memberNew;
    }

    /**
     * 保存或更新memberInfo的健康信息
     *
     * @param memberInfo memberInfo
     * @param currentId  用户id
     */
    public void updateMemberInfoHealth(MemberInfo memberInfo, String currentId) {
        // 保存健康信息
        MemberInfo dbMemberInfo = memberInfoService.findByMemberId(currentId);
        if (dbMemberInfo == null) {
            dbMemberInfo = new MemberInfo();
            dbMemberInfo.setMemberId(currentId);
        }
        dbMemberInfo.setIsGm(memberInfo.getIsGm());
        dbMemberInfo.setIsPx(memberInfo.getIsPx());
        dbMemberInfo.setIsDx(memberInfo.getIsDx());
        dbMemberInfo.setIsYf(memberInfo.getIsYf());
        dbMemberInfo.setIsDxt(memberInfo.getIsDxt());
        dbMemberInfo.setIsGxy(memberInfo.getIsGxy());
        dbMemberInfo.setIsXzb(memberInfo.getIsXzb());
        dbMemberInfo.setIsXjqy(memberInfo.getIsXjqy());
        dbMemberInfo.setIsGgj(memberInfo.getIsGgj());
        dbMemberInfo.setHealthInfo(PinyinUtil.filterEmoji(memberInfo.getHealthInfo(), ""));
        if (StringUtils.isEmpty(dbMemberInfo.getId())) {
            memberInfoService.insert(dbMemberInfo);
        } else {
            memberInfoService.update(dbMemberInfo);
        }
    }

    /**
     * 日期格式
     *
     * @param infoItineraries
     */
    public void formatItineraryTime(List<GatherInfoItinerary> infoItineraries) {
        if (CollectionUtils.isNotEmpty(infoItineraries)) {
            for (GatherInfoItinerary itinerary : infoItineraries) {
                if (itinerary.getDepartTime() != null) {
                    String formatDate = DateUtils.formatDate(itinerary.getDepartTime(), "yyyy-MM-dd HH:mm");
                    itinerary.setDepartDate(formatDate);
                }
                if (itinerary.getArrivalTime() != null) {
                    String formatDate = DateUtils.formatDate(itinerary.getArrivalTime(), "yyyy-MM-dd HH:mm");
                    itinerary.setArrivalDate(formatDate);
                }
            }
        }
    }

    public void formatRoomTime(GatherInfoMember gatherInfoMember) {
        if (gatherInfoMember != null) {
            if (gatherInfoMember.getRoomStartTime() != null) {
                String startDate = DateUtils.formatDate(gatherInfoMember.getRoomStartTime(), "yyyy-MM-dd");
                gatherInfoMember.setRoomStartDate(startDate);
            }
            if (gatherInfoMember.getRoomEndTime() != null) {
                String endDate = DateUtils.formatDate(gatherInfoMember.getRoomEndTime(), "yyyy-MM-dd");
                gatherInfoMember.setRoomEndDate(endDate);
            }
        }
    }

    /**
     * 转换日期
     *
     * @param infoItineraries
     * @throws ParseException
     */
    public void parseItineraryTime(List<GatherInfoItinerary> infoItineraries) throws ParseException {
        if (CollectionUtils.isNotEmpty(infoItineraries)) {
            for (GatherInfoItinerary itinerary : infoItineraries) {
                // 出发时间
                if (StringUtils.isNotEmpty(itinerary.getDepartDate())) {
                    Date departTime = DateUtils.parse(itinerary.getDepartDate().replace("T", " "), "yyyy-MM-dd HH:mm");
                    itinerary.setDepartTime(departTime);
                } else {
                    itinerary.setDepartTime(null);
                }
                // 到达时间
                if (StringUtils.isNotEmpty(itinerary.getArrivalDate())) {
                    Date arrivalTime = DateUtils.parse(itinerary.getArrivalDate().replace("T", " "), "yyyy-MM-dd HH:mm");
                    itinerary.setArrivalTime(arrivalTime);
                } else {
                    itinerary.setArrivalTime(null);
                }
            }
        }
    }

    /**
     * 转换日期
     * @param gatherInfoMember
     * @throws ParseException
     */
    public void parseRoomTime(GatherInfoMember gatherInfoMember) throws ParseException {
        if (gatherInfoMember != null) {
            if (StringUtils.isNotEmpty(gatherInfoMember.getRoomStartDate())) {
                Date startTime = DateUtils.parse(gatherInfoMember.getRoomStartDate(), "yyyy-MM-dd");
                gatherInfoMember.setRoomStartTime(startTime);
            }
            if (StringUtils.isNotEmpty(gatherInfoMember.getRoomEndDate())) {
                Date endTime = DateUtils.parse(gatherInfoMember.getRoomEndDate(), "yyyy-MM-dd");
                gatherInfoMember.setRoomEndTime(endTime);
            }
        }
    }

    /**
     * 新增或保存行程信息
     *
     * @param infoItineraries 行程信息
     * @param type            类型 go/back
     * @param infoMemberId    关联id
     * @throws Exception
     */
    public void saveOrUpdate(List<GatherInfoItinerary> infoItineraries, String type, String infoMemberId, List<GatherInfoItinerary> gos) throws Exception {
        if ("go".equals(type)) {
            List<String> newIds = LangUtils.transform(infoItineraries, input -> input.getId());

            List<String> oldIds = LangUtils.transform(gos, input -> input.getId());
            boolean flag = oldIds.removeAll(newIds);

            if (flag) {
                for (String goId : oldIds) {
                    gatherInfoItineraryService.delete(goId);
                }
            }
        }
        for (int i = 0; i < infoItineraries.size(); i++) {
            GatherInfoItinerary itinerary = infoItineraries.get(i);
            if (StringUtils.isEmpty(itinerary.getId())) {
                itinerary.setSort(i + 1);
                itinerary.setInfoMemberId(infoMemberId);
                itinerary.setType(type);
                gatherInfoItineraryService.insert(itinerary);
            } else {
                GatherInfoItinerary dbItinerary = gatherInfoItineraryService.get(itinerary.getId());
                MyBeanUtils.copyBeanNotNull2Bean(itinerary, dbItinerary);
                gatherInfoItineraryService.update(dbItinerary);
            }
        }
    }

    /**
     * 转换日期
     *
     * @param infoItineraries
     * @throws ParseException
     */
    public void parseItineraryTime2(List<GatherInfoItinerary> infoItineraries) throws ParseException {
        if (CollectionUtils.isNotEmpty(infoItineraries)) {
            for (GatherInfoItinerary itinerary : infoItineraries) {
                // 出发时间
                if (StringUtils.isNotEmpty(itinerary.getDepartDate())) {
                    Date departTime = DateUtils.parse(itinerary.getDepartDate(), "yyyy-MM-dd HH:mm");
                    itinerary.setDepartTime(departTime);
                } else {
                    itinerary.setDepartTime(null);
                }
                // 到达时间
                if (StringUtils.isNotEmpty(itinerary.getArrivalDate())) {
                    Date arrivalTime = DateUtils.parse(itinerary.getArrivalDate(), "yyyy-MM-dd HH:mm");
                    itinerary.setArrivalTime(arrivalTime);
                } else {
                    itinerary.setArrivalTime(null);
                }
            }
        }
    }

    /**
     * 保存信息收集项目
     *
     * @param businessId 事项/活动id
     * @param activity
     * @param type
     * @param opId
     * @return 信息收集项目id
     */
    public String createGatherInfoProjectBusiness(String businessId, Activity activity, String type, String opId) {
        CompetitionBusiness cBusiness = competitionBusinessService.findByBusinessId(businessId, type);
        if (cBusiness == null) {
            cBusiness = new CompetitionBusiness();
            cBusiness.setBusinessId(businessId);
            cBusiness.setType(type);
            cBusiness.setCreateBy(opId);
            cBusiness.setUpdateBy(opId);
            String competitionId = insertOrUpdateProject("", activity.getTitle(), activity.getPic(), activity.getMember());
            cBusiness.setCompetitionId(competitionId);
            competitionBusinessService.insert(cBusiness);
            return competitionId;
        } else {
            GatherInfoProject infoProject = gatherInfoProjectService.get(cBusiness.getCompetitionId());
            if (infoProject == null) {
                String competitionId = insertOrUpdateProject("", activity.getTitle(), activity.getPic(), activity.getMember());
                cBusiness.setCompetitionId(competitionId);
                competitionBusinessService.update(cBusiness);

                return competitionId;
            }
            return cBusiness.getCompetitionId();
        }
    }

    /**
     * 添加人员
     *
     * @param projectId  项目id
     * @param memberActs 报名人员
     * @param createBy   创建者
     */
    public void addMember(String projectId, List<MemberAct> memberActs, String createBy) {
        // 报名人员
        List<String> actMemberIds = (List<String>) CollectionUtils.collect(memberActs, new Transformer() {

            @Override
            public Object transform(Object input) {
                MemberAct mm = (MemberAct) input;
                return mm.getMemberId();
            }
        });

        Set<String> newActMemberIds = Sets.newHashSet(actMemberIds);

        List<GatherInfoMember> infoMembers = gatherInfoMemberService.findByProject(projectId);
        List<String> infoMemberIds = (List<String>) CollectionUtils.collect(infoMembers, new Transformer() {
            @Override
            public Object transform(Object input) {
                GatherInfoMember mm = (GatherInfoMember) input;
                return mm.getMemberId();
            }
        });

        // 添加未加入项目的报名人员
        newActMemberIds.removeAll(infoMemberIds);

        for (String memberId : newActMemberIds) {
            insertMember(projectId, memberId, createBy);
        }
    }

    /**
     * 新增或编辑项目
     *
     * @param projectId id
     * @param title     标题
     * @param picture   图片
     * @param createBy  创建者
     * @return
     */
    public String insertOrUpdateProject(String projectId, String title, String picture, String createBy) {
        GatherInfoProject infoProject = gatherInfoProjectService.get(projectId);
        if (infoProject == null) {
            infoProject = new GatherInfoProject();
            infoProject.setCreateBy(createBy);
        }
        infoProject.setTitle(title);
        infoProject.setUpdateBy(createBy);
        infoProject.setPicture(picture);
        if (StringUtils.isEmpty(infoProject.getId())) {
            gatherInfoProjectService.insert(infoProject);
        } else {
            gatherInfoProjectService.update(infoProject);
        }
        return infoProject.getId();
    }

    /**
     * 添加人员
     *
     * @param projectId 项目id
     * @param memberId  用户id
     * @param createBy  创建者
     */
    public void insertMember(String projectId, String memberId, String createBy) {
        GatherInfoMember gatherInfoMember = new GatherInfoMember();
        gatherInfoMember.setProjectId(projectId);
        gatherInfoMember.setMemberId(memberId);
        gatherInfoMember.setUpdateBy(createBy);
        gatherInfoMember.setCreateBy(createBy);


        Member member = memberService.get(memberId);
        if (member != null) {
            gatherInfoMember.setBaseStatus(member.getPerfectState());
        }
        MemberInfo memberInfo = memberInfoService.findByMemberId(memberId);
        if (memberInfo != null) {
            gatherInfoMember.setInsuranceStatus(memberInfo.getPerfectState());
        }
        gatherInfoMemberService.insert(gatherInfoMember);
    }
}
